<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="用户管理">
        <template slot="btn">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="small"
                v-hasPermi="{v:['sys:user:add']}" @click="handleAdd">新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" icon="el-icon-edit" v-hasPermi="{v:['sys:user:edit']}"
                :disabled="single" size="small" @click="handleUpdate">修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" :disabled="multiple" size="small"
                v-hasPermi="{v:['sys:user:delete']}" @click="handleDelete">删除
              </el-button>
            </el-col>
          </el-row>
        </template>
      </modules-title>
    </div>
    <div style="padding:20px">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small"
              @blur="blurIn($event)" @keyup.enter.native="handleInput" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" default-expand-all
              @node-click="handleNodeClick" />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px"
            size="small">
            <el-form-item label="用户名称" style="margin-right:40px">
              <el-input v-model="queryParams.user_name" placeholder="请输入用户名称" clearable
                style="width: 180px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号码" style="margin-right:40px">
              <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable
                style="width: 180px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" style="margin-right:40px">
              <el-select v-model="queryParams.user_status" placeholder="用户状态" clearable
                style="width: 180px">
                <el-option v-for="dict in statusOptions" :key="dict.key" :label="dict.value"
                  :value="dict.key" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd"
              type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索
              </el-button>
              <el-button plain icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!--表格-->
          <el-table :data="userList" @selection-change="handleSelectionChange"
            :row-key="(row)=>{ return row.id}" ref="multipleTable" tooltip-effect="dark" border
            size="medium">
            <el-table-column type="selection" width="50" align="center" :reserve-selection="true" />
            <el-table-column label="编号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="用户名称" align="center" prop="user_name"
              :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" prop="deptName"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.department !== undefined && scope.row.department !== null">{{scope.row.department.department_name}}</span>
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center" prop="roleInfo"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.is_admin === true">超级管理员</span>
                <span v-else v-for="(item,index) of scope.row.role" :key="index">
                  {{item.role_name}} </span>

              </template>
            </el-table-column>
            <el-table-column label="手机号码" align="center" prop="phone" width="120" />
            <el-table-column label="状态" align="center" width="120">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.user_status" :active-value="1" :inactive-value="-1"
                  @change="handleStatusChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="create_time" width="180">
              <template slot-scope="scope">
                <span>{{ dateFormat1('yyyy-mm-dd HH:MM:SS',scope.row.created_at)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template slot-scope="scope">
                <el-button size="medium" type="text" icon="el-icon-edit"
                  v-hasPermi="{v:['sys:user:edit']}" @click="handleUpdate(scope.row)">修改
                </el-button>
                <el-button size="medium" type="text" icon="el-icon-key"
                  @click="handleResetPwd(scope.row)">重置
                </el-button>
                <el-button v-if="!scope.row.is_admin" size="medium" type="text"
                  icon="el-icon-delete" v-hasPermi="{v:['sys:user:delete']}" style="color:red"
                  @click="handleDelete(scope.row)">
                  删除
                </el-button>

              </template>
            </el-table-column>
          </el-table>
          <!--页码-->
          <pagination style="display:flex;justify-content:flex-end;" :total="total"
            :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="pagination" />
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
      :before-close="cancel" :close-on-click-modal="false" v-if="open">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="user_name">
              <el-input v-model="form.user_name" placeholder="用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="department_id">
              <el-cascader v-model="form.department_id" :options="deptOptions" placeholder="请选择归属部门"
                ref="refHandle" :show-all-levels="false" @change="onChange" :key="isResouceShow"
                :props="{ expandTrigger: 'hover',checkStrictly: true ,label:'department_name',value:'id'}">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id === undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" autocomplete="new-password"
                type="password" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sexOptions" :key="dict.key" :label="dict.value"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.user_status">
                <el-radio v-for="dict in statusOptions" :key="dict.key" :label="dict.key">
                  {{dict.value}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色" prop="role_code" v-if="boole">
              <el-select v-model="form.role_code" style="width:480px" multiple placeholder="请选择角色">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.role_name"
                  :value="item.role_code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  user,
  depaList,
  roleList,
  userList,
  deleteList,
  userStatus,
  userUpdate,
  userPwd,
  existMobile,
  existEmail
} from "@/api/authorization";
import store from "@/store";

export default {
  data() {
    var self = this;
    let phonePass = (rule, value, callback) => {
      let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      if (value === undefined || value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("手机号码格式错误"));
        } else {
          this.isMobileExist(value, function(data) {
            if (!data.state) {
              callback();
            } else {
              callback(new Error("该手机号已存在！"));
            }
          });
        }
      }
    };
    let emailPass = (rule, value, callback) => {
      let reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (value === undefined || value === "") {
        callback(new Error("请输入邮箱号"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("邮箱格式错误"));
        } else {
          this.isEmailExist(value, function(data) {
            if (!data.state) {
              callback();
            } else {
              callback(new Error("该邮箱已存在！"));
            }
          });
        }
      }
    };
    return {
      single: true, //非单个禁用
      multiple: true, // 非多个禁用
      deptName: "",
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "department_name"
      },
      queryParams: {
        //状态数据字典
        pageNum: 1,
        pageSize: 10,
        user_name: "",
        phone: "",
        user_status: ""
      },
      dateRange: [], //日期范围
      statusOptions: [
        { key: -1, value: "停用" },
        { key: 1, value: "启用" }
      ], //状态数据字典
      userList: [], //表格数据
      ids: [], // 选中数组id
      listArr: [], //选中数组
      open: false,
      title: "", //弹框名字
      form: {
        sex: "男",
        role_code: []
      }, //弹框表单
      rules: {
        user_name: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        department_id: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ],
        email: [{ required: true, validator: emailPass, trigger: "blur" }],
        phone: [{ required: true, validator: phonePass, trigger: "blur" }],
        role_code: [
          { required: true, message: "角色选择不能为空", trigger: "change" }
        ]
      }, //弹框表单校验
      sexOptions: [
        { key: "1", value: "男" },
        { key: "2", value: "女" }
      ], //弹框性别
      roleOptions: [], //弹框角色
      total: 0,
      department_id: "",
      boole: true,
      aaa: [],
      id: "",
      isResouceShow: 0
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.handleDepa();
    this.handleUserData();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    setInterval(function() {
      document.querySelectorAll(".el-cascader-node__label").forEach(el => {
        el.onclick = function() {
          if (this.previousElementSibling) this.previousElementSibling.click();
        };
      });
    }, 1000);
  },
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，未调用不会执行，只执行逻辑，返回值可有可无
  methods: {
    //获取部门列表
    handleDepa() {
      let data = {
        department_status: 0,
        department_name: ""
      };
      depaList(data).then(res => {
        if (res.code === 200) {
          this.deptOptions = res.data || [];
          ++this.isResouceShow;
        }
      });
    },
    //递归部门
    recursive(arr, id) {
      let list = [];
      let self = this;

      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].id) {
          list.push(arr[i].id);
          return list;
        } else if (arr[i].children && arr[i].children.length > 0) {
          let list1 = this.recursive(arr[i].children, id);
          if (list1 && list1.length > 0) {
            list.push(arr[i].id);
            return (list = list.concat(list1));
          }
        }
      }
    },
    //获取用户列表
    handleUserData() {
      let data = {
        limit: this.queryParams.pageSize,
        skip: this.queryParams.pageNum,
        department_id: this.department_id,
        phone: this.queryParams.phone,
        user_name: this.queryParams.user_name,
        user_status: this.queryParams.user_status
      };
      userList(data).then(res => {
        if (res.code === 200) {
          this.userList = res.data.data || [];
          this.total = res.data.total;
        }
      });
    },
    //页码条数
    pagination(val) {
      this.queryParams.pageNum = val.page;
      this.queryParams.pageSize = val.limit;
      this.handleUserData();
    },
    //搜索
    blurIn(value) {
      if (value.target.value === "") {
        this.department_id = "";
        this.handleUserData();
      }
    },
    handleInput(e) {
      let keyCode = window.event ? e.keyCode : e.which;
      if (keyCode === 13 && this.deptName === "") {
        this.department_id = "";
        this.handleUserData();
      }
    },
    //筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.department_name.indexOf(value) !== -1;
    },
    //节点单击事件
    handleNodeClick(data) {
      this.department_id = data.id;
      this.handleUserData();
    },
    //获取角色
    handleRole() {
      let data = {
        condition: {
          role_name: "",
          role_code: ""
        },
        pager: {
          skip: 1,
          limit: 50
        }
      };

      roleList(data).then(res => {
        if (res.code === 200) {
          this.roleOptions = res.data.data || [];
        }
      });
    },
    //新增
    handleAdd() {
      this.open = true;
      this.title = "新增用户";
      this.handleRole();
      let _self = this;
      _self.$nextTick(() => {
        _self.$set(_self.form, "role_code", []);
      });
      this.id = "";
      console.log(this.id);
    },
    //修改
    handleUpdate(row) {
      let _self = this;
      const ID = row.id || _self.ids;
      this.id = ID;
      const list = _self.listArr[0] || row;
      let role = [],
        department = [];
      if (list.is_admin) {
        this.boole = false;
        role = ["*"];
      } else {
        this.boole = true;
        this.handleRole();
        list.role.forEach(item => {
          role.push(item.role_code);
        });
      }
      if (list.department === null) {
        department = [];
      } else {
        department = _self.recursive(_self.deptOptions, list.department.id);
      }
      this.open = true;
      this.title = "修改用户";
      this.form = {
        id: list.id,
        phone: list.phone,
        email: list.email,
        department_id: department,
        user_name: list.user_name,
        user_status: list.user_status,
        sex: list.sex,
        remark: list.remark
      };
      _self.$set(_self.form, "role_code", role);
      if (list.id === _self.$store.getters.userInfo.user.id) {
        _self.$store.dispatch("user/getInfo");
      }
    },
    //删除
    handleDelete(row) {
      let ids = [];
      if (this.ids.length === 0) {
        ids = [row.id];
      } else {
        ids = this.ids;
      }
      let data = {
        ids: ids
      };
      let a = [];
      if (this.aaa.length > 0) {
        for (let i = 0; i < this.aaa.length; i++) {
          a.push(this.aaa[i].index);
        }
        let b = `编号为${a.join(",")}的是超级管理员不能删除`;
        this.$message.error(b);
        return;
      }
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteList(data).then(res => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              if (this.userList.length === 1) {
                this.queryParams.pageNum -= 1;
              }
              this.$refs.multipleTable.clearSelection();
              this.handleUserData();
            }
          });
        })
        .catch(() => {});
    },
    //重置密码
    handleResetPwd(row) {
      let data = {};
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          data = {
            id: row.id,
            pass_word: value
          };
          userPwd(data).then(res => {
            if (res.code === 200) {
              this.$message.success("更新成功");
            }
          });
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        department_id: undefined, // 所属部门
        user_name: undefined, //用户昵称
        password: undefined, //密码
        phone: undefined, //手机
        email: undefined, //邮箱
        sex: "男", //性别
        user_status: undefined, //状态
        remark: undefined, //备注
        role_code: [] //角色
      };
      this.resetForm("form");
    },
    //回车事件
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.handleUserData();
    },
    //重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        user_name: "",
        phone: "",
        user_status: ""
      };
      this.department_id = "";
      this.handleUserData();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.listArr = [...new Set(selection)];
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      let that = this;
      for (let i = 0; i < that.ids.length; i++) {
        let index = that.userList.findIndex(
          a => a.id == that.ids[i] && a.is_admin == true
        );
        if (index != -1) {
          let data = {
            index:
              (that.queryParams.pageNum - 1) * that.queryParams.pageSize +
              index +
              1,
            id: that.ids[i]
          };
          if (that.aaa.findIndex(a => a.id == data.id) == -1) {
            that.aaa.push(data);
          }
        }
      }
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.user_status === 1 ? "启用" : "停用";
      let data = {
        id: row.id,
        user_status: row.user_status
      };
      this.$confirm(
        '确认要"' + text + '""' + row.user_name + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          userStatus(data).then(res => {
            if (res.code === 200) {
              this.handleUserData();
            }
          });
        })
        .catch(() => {
          row.user_status = row.user_status === -1 ? 1 : -1;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //提交按钮
    submitForm() {
      if (this.form.department_id && this.form.department_id instanceof Array) {
        this.form.department_id = this.form.department_id[
          this.form.department_id.length - 1
        ];
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id === undefined) {
            user(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success("新增成功");
                this.open = false;
                this.reset();
                this.handleUserData();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            userUpdate(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success("修改成功");
                this.open = false;
                this.reset();
                this.handleUserData();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    //弹框部门
    onChange(val) {
      if (val !== null && val) {
        this.form.department_id = val[val.length - 1];
        this.$refs.refHandle.dropDownVisible = false;
        this.$refs.form.fields.map(i => {
          if (i.prop === "department_id") {
            i.clearValidate();
          }
        });
      }
    },
    //手机验证是否存在
    isMobileExist(mobile, callback) {
      var data = {
        mobile: mobile,
        id: this.id
      };
      existMobile(data).then(res => {
        if (res.code == 200) {
          callback({ state: res.data.is_exist });
        }
      });
    },
    isEmailExist(email, callback) {
      var data = {
        email: email,
        id: this.id
      };
      existEmail(data).then(res => {
        if (res.code == 200) {
          callback({ state: res.data.is_exist });
        }
      });
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
::v-deep .el-button--medium {
  padding: 0;
}
</style>
